import { BaseDirectory, exists, readTextFile, writeTextFile, mkdir } from '@tauri-apps/plugin-fs';
import type { DailyReport } from './types';

const DATA_FILE = 'daily-reports.json';
const DATA_DIR = 'rbao-data';

// 跨平台的基础目录选择
function getBaseDirectory(): BaseDirectory {
  // 在Windows上优先使用AppLocalData，其他平台使用AppData
  if (typeof window !== 'undefined' && navigator.platform.toLowerCase().includes('win')) {
    return BaseDirectory.AppLocalData;
  }
  return BaseDirectory.AppData;
}

export class StorageService {
  private static instance: StorageService;
  
  static getInstance(): StorageService {
    if (!StorageService.instance) {
      StorageService.instance = new StorageService();
    }
    return StorageService.instance;
  }

  private async ensureDataDirectory(): Promise<void> {
    try {
      const baseDir = getBaseDirectory();
      const dirExists = await exists(DATA_DIR, { baseDir });
      if (!dirExists) {
        await mkdir(DATA_DIR, { baseDir, recursive: true });
      }
    } catch (error) {
      console.error('Failed to create data directory:', error);
    }
  }

  private async getFilePath(): Promise<string> {
    await this.ensureDataDirectory();
    return `${DATA_DIR}/${DATA_FILE}`;
  }

  async loadReports(): Promise<DailyReport[]> {
    try {
      const filePath = await this.getFilePath();
      const baseDir = getBaseDirectory();
      const fileExists = await exists(filePath, { baseDir });
      
      if (!fileExists) {
        return [];
      }

      const content = await readTextFile(filePath, { baseDir });
      const reports = JSON.parse(content) as DailyReport[];
      
      // 验证数据格式
      if (!Array.isArray(reports)) {
        console.warn('Invalid data format, returning empty array');
        return [];
      }
      
      return reports;
    } catch (error) {
      console.error('Failed to load reports:', error);
      return [];
    }
  }

  async saveReports(reports: DailyReport[]): Promise<boolean> {
    try {
      const filePath = await this.getFilePath();
      const content = JSON.stringify(reports, null, 2);
      const baseDir = getBaseDirectory();
      
      await writeTextFile(filePath, content, { baseDir });
      return true;
    } catch (error) {
      console.error('Failed to save reports:', error);
      return false;
    }
  }

  async addReport(report: DailyReport): Promise<boolean> {
    try {
      const reports = await this.loadReports();
      reports.push(report);
      return await this.saveReports(reports);
    } catch (error) {
      console.error('Failed to add report:', error);
      return false;
    }
  }

  async updateReport(updatedReport: DailyReport): Promise<boolean> {
    try {
      const reports = await this.loadReports();
      const index = reports.findIndex(r => r.id === updatedReport.id);
      
      if (index === -1) {
        console.warn('Report not found for update');
        return false;
      }
      
      reports[index] = { ...updatedReport, updatedAt: new Date().toISOString() };
      return await this.saveReports(reports);
    } catch (error) {
      console.error('Failed to update report:', error);
      return false;
    }
  }

  async deleteReport(id: string): Promise<boolean> {
    try {
      const reports = await this.loadReports();
      const filteredReports = reports.filter(r => r.id !== id);
      
      if (filteredReports.length === reports.length) {
        console.warn('Report not found for deletion');
        return false;
      }
      
      return await this.saveReports(filteredReports);
    } catch (error) {
      console.error('Failed to delete report:', error);
      return false;
    }
  }
}
